package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;



import dataTypes.*;

/*
 * Gets all active to display to user
 */

@SuppressWarnings("serial")
public class getAllCoupons extends HttpServlet {

	public getAllCoupons() {
		super();
	}

	@SuppressWarnings("deprecation")
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			UserService userService = UserServiceFactory.getUserService();
			List<deal> results=appManager.getInstance().getDeals();
			response.setCharacterEncoding("UTF-8"); 
			response.setContentType("text/html; charset=UTF-8");
			response.setHeader("Content-Encoding","UTF-8");

			String username = request.getParameter("username");
			String UA = request.getHeader("User-Agent").toLowerCase();

			if (UA.contains("iphone") || UA.contains("android") || UA.contains("package")) {


				response.getWriter().println("<html>");
				response.getWriter().println("<head>");
				response.getWriter().println("<title>CoupoNow</title>");

				response.getWriter().println("<link type='text/css' rel='stylesheet' media='screen' href='/jqtouch/themes/jqt/theme.css' charset='utf-8'>");
				response.getWriter().println("<link type='text/css' rel='stylesheet' media='screen' href='/jqtouch/jqtouch/jqtouch.css' charset='utf-8'>");
				response.getWriter().println("<script type='text/javascript' src='http://maps.google.com/maps/api/js?libraries=geometry&sensor=true&language=iw&region=IL' charset='utf-8'></script>");
				response.getWriter().println("<script type='text/javascript' src='http://code.google.com/apis/gears/gears_init.js' charset='utf-8'></script>");
				response.getWriter().println("<script src='/jqtouch/jqtouch/jquery-1.4.2.js'></script>");
				response.getWriter().println("<script type='application/x-javascript' src='/jqtouch/jqtouch/jqtouch.js' charset='utf-8'></script>");
				response.getWriter().println("<script type='application/x-javascript' src='/jqtouch/extensions/jqt.location.js' charset='utf-8'></script>");
				response.getWriter().println("<script type='text/javascript'>");
				response.getWriter().println("var jQT =  new $.jQTouch({ icon: 'heading1.png', startupScreen: 'splashscreen.png'});");//useAnimations: 'false'
				response.getWriter().println("</script>");
				
				response.getWriter().println("<script type='text/javascript'>");
				response.getWriter().println("var initialLocation; var xy; var xyz; var curPos;");
				response.getWriter().println("function initialize() {");
				response.getWriter().println("if(navigator.geolocation) {navigator.geolocation.getCurrentPosition(succ,err,{ enableHighAccuracy: true });}");
				response.getWriter().println("else if (google.gears) {var geo = google.gears.factory.create('beta.geolocation');");
				response.getWriter().println("geo.getCurrentPosition(succ1, err, { enableHighAccuracy: true } ); }}");
				response.getWriter().println("function succ1 (position) {xy = position.latitude; xyz = position.longitude; curPos =  new google.maps.LatLng(xy, xyz);}");
				response.getWriter().println("function succ (position) {xy = position.coords.latitude; xyz = position.coords.longitude; curPos =  new google.maps.LatLng(xy, xyz);}");
				response.getWriter().println("function err(){alert('cant get current location!');}");
				response.getWriter().println("</script>");
				response.getWriter().println("</head>");

				response.getWriter().println("<body onLoad='initialize()'>");
				response.getWriter().println("<div id=\"jqt\">");
				response.getWriter().println("<div id='home' selected='true'>");
				response.getWriter().println("<div class='toolbar'>");
				response.getWriter().println("<h1><img src='heading1.png' width='110px' height='38px'/></h1>");
				response.getWriter().println("<a href='#about' class='button rightButton'>אודות</a>");
				response.getWriter().println("<a href='/getcoupons?gName=" + username + "' target='_webapp' class='button leftButton'>עסקאות שלי</a>");
				response.getWriter().println("</div>");
				response.getWriter().println("<ul id='lst'>");
int i = 8;
				for (deal d:results){
					double percent = d.getPercent()*100 / d.getAmount();
					i += 2;
					
					response.getWriter().println("<script type='text/javascript'>var geocoder; var loc"+ i +"; var dis; geocoder = new google.maps.Geocoder();" +
							"var address ='" + d.getBusiness().getAddress() + "';" +
							"geocoder.geocode( { 'address': address}, function(results, status) {if (status == google.maps.GeocoderStatus.OK) {" +
							"loc" + i + "= results[0].geometry.location;}});" +
							"setTimeout(\"dis = (google.maps.geometry.spherical.computeDistanceBetween(curPos, loc" + i + ") / 1000); document.getElementById('dis"+ d.getKey().getId() +"').innerHTML =  dis.toFixed(1) + ' Km';\",85"+ i + ");" +

							"</script>");
					
					
					response.getWriter().println("<li class='arrow' style='text-align:right'><a href ='#deal"+ d.getKey().getId() +"'><strong> שם העסק:  </strong>" +	d.getBusiness().getBusiness() + "<strong> הנחה:  </strong>" +(int)percent + 
							"% <img src='" + d.getBusiness().getPhotoLink() + "'height='40' width='40' style='float:right; margin-left:6px;'/><BR>" +
							"<strong> בתוקף עד:  </strong>" + d.getEnd().getHours()+ ":" + d.getEnd().getMinutes()+  "<BR><div id='dis" + d.getKey().getId()  + "' style='float:left;padding-left:100px;'>...מחשב</div>"+ "  :מרחק   " + "</a> </li>");
				}

				response.getWriter().println("</ul>");
				response.getWriter().println("</div>");


				for (deal d:results){					
					double percent = d.getPercent()*100 / d.getAmount();
					response.getWriter().println("<div id='deal"+ d.getKey().getId() + "'>");
					response.getWriter().println("<div class='toolbar'>");
					response.getWriter().println("<h1><img src='heading1.png' width='110px' height='38px'/></h1>");
					response.getWriter().println("<a href='#home' class='button back'>חזור</a>");
					response.getWriter().println("</div>");

					response.getWriter().println("<div id='inf' class='dealinfo'>");				
					response.getWriter().println("<ul class='dealinfoLIST'>");
					/*image*/			response.getWriter().println("<li class = 'dealinfoLIST' style='height:150px;'><a href ='" + d.getBusiness().getSiteLink()+ "' rel='external'> <img src='" + d.getBusiness().getPhotoLink() + "' height='140' width='70%'/></a>  </li> ");
					/*description*/		response.getWriter().println("<li class = 'dealinfoLIST' style='text-align:right; color:#000'>" + d.getBusiness().getDescription() + "</li>");
					/*Discount*/		response.getWriter().println("<li class = 'dealinfoLIST' style='text-align:right;color:#000'> !רק היום: " + (int)percent + "  אחוזי הנחה" + "</li>");
					/*Num+Valid Until*/ response.getWriter().println("<li class = 'dealinfoLIST' style='text-align:right;color:#000'> רק " + d.getAmount() + "  קופונים" + "<BR> בתוקף החל מ: " + d.getStart().getHours() + ":" + d.getStart().getMinutes() 
							+ "<BR> בתוקף עד: " + d.getEnd().getHours() + ":" + d.getEnd().getMinutes() + "</li>");
					
					if (username != null){
						response.getWriter().println("<li class = 'dealinfoLIST' style='height:50px; margin-top:36px; text-align:right; color:#000'><a href='/useraddcoupon?bId=" +
								d.getBusiness().getKey().getId() + "&dId="  + d.getKey().getId() + "&uId=" + username +  "&num=1" +   "' target='_webapp' class='whiteButton'>קח קופון</a></li>");
					}
					else{  /*Get Coupon! iPhone*/
						response.getWriter().println("<li class = 'dealinfoLIST' style='height:50px; margin-top:36px; text-align:right; color:#000'><a href=\"javascript:location.replace('/useraddcoupon?bId=" +
								d.getBusiness().getKey().getId() + "&dId="  + d.getKey().getId() + "&uId=notAndroidApp" +  "&num=1" +   "')\" target='_webapp' class='whiteButton'>קח קופון</a></li>");
					}
					
					/*Facebook like*/	response.getWriter().println("<li class = 'dealinfoLIST' style='text-align:center; color:#000'>	<div id='fb-root'></div>" +
							"<script src='http://connect.facebook.net/en_US/all.js#xfbml=1'></script><fb:like href='coupon-now.appspot.com' send='false' layout='button_count' width='100' show_faces='false' action='recommend' font=''></fb:like></li>");					
					response.getWriter().println("</ul>");				
					response.getWriter().println("</div>");
					response.getWriter().println("</div>");		

				}

				response.getWriter().println("<div id='about' style='text-align:right'>");
				response.getWriter().println("<div class='toolbar'>");
				response.getWriter().println("<h1><img src='heading1.png' width='110px' height='38px'/></h1>");
				response.getWriter().println("<a href='#home' class='button back'>חזור</a>");
				response.getWriter().println("</div>");
				response.getWriter().println("מי אנחנו? <BR><BR> קופונאו הוא דרך חדשה,מהנה ומידית להינות מכל הטוב שבעולם הקופונים <BR> ראית קופון שמוצא חן בעיניך? קח אותו! קוד אישור ישלח לכתובת הדואר האלקטרוני שלך <BR><BR> Contact Details: couponnowmobile@gmail.com");
				response.getWriter().println("</div>");
				response.getWriter().println("</div>");
				response.getWriter().println("</body>");
				response.getWriter().println("</html>");

			}
			else{
				response.getWriter().println("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
				response.getWriter().println("<html>");
				response.getWriter().println("<head>");
				response.getWriter().println("<style type='text/css'> body {background-image:url('light_blue.jpg');}</style>");
				response.getWriter().println("<title>CoupoNow</title>");
				response.getWriter().println("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>");
				response.getWriter().println("<link type='text/css' rel='stylesheet' href='couponow.css'>");
				response.getWriter().println("</head>");

				response.getWriter().println("<body>");
				response.getWriter().println("<div id='general'>");
				response.getWriter().println("<div id='heading'>");
				response.getWriter().println("<div id='image'><a href='/'><img src='heading1.png' class='img1' alt='Logo' style='border-style:none'/></a></div>");
				response.getWriter().println("<div id='yoursource'>");
				response.getWriter().println("<img src='pic1.png' height='126' width='540'/>");
				response.getWriter().println("</div>");
				response.getWriter().println("</div>");
				response.getWriter().println("<br class='clearfloat'/>");

				response.getWriter().println("<div id='body'>");
				response.getWriter().println("<div id='activeDeals'><img src='pic2.png' height='52' width='325'/></div>");
				response.getWriter().println("<div id='data'>");

				for (deal d: results){
					double percent = d.getPercent()*100 / d.getAmount();
					response.getWriter().println("<div class='dls'><strong> שם העסק: </strong>" + d.getBusiness().getBusiness() +
							"<strong>  אחוז הנחה: </strong>" + (int)percent + 
							" <strong>  שעת סיום: </strong>" + d.getEnd().getHours()+ ":" + d.getEnd().getMinutes() +
							" <img src='" + d.getBusiness().getPhotoLink() +  "'class='img2'style='margin-left:12px;'/></div>") ;
				}

				response.getWriter().println("</div>");
				response.getWriter().println("<br class='clearfloat'/>");
				response.getWriter().println("<div id='bussiness' class='bottom_text'> בעל עסק? <a href='adminlogin.html'>כנס כאן</a></div>");
				response.getWriter().println("</div>");
				response.getWriter().println("</div>");

				response.getWriter().println("</body>");
				response.getWriter().println("</html>");

			}
		} catch (Exception e) { 
			e.printStackTrace();
		}		
	}


	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			/* deals DB access here - all deals */

			// send back to client as arrayList:

		} catch (Exception e) { 
			e.printStackTrace();
		}		
	}
}
